/**
 *====================================================
 * 文件名称: PickupApplicationCastor.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年11月26日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1.dto;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yuexunit.core.BusinessException;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.project.action.v1.model.PickupApplication;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.ExchangeBulkstockInfo;
import com.yuexunit.finance.project.action.v1.model.output.ExchangeContainerBulkstock;
import com.yuexunit.finance.project.action.v1.model.output.ExchangeContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.PickupApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupApplicationLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.PickupDelayApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupDelayApplicationLineInfo;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceContractEntity;
import com.yuexunit.finance.project.entity.PickupApplicationEntity;
import com.yuexunit.finance.project.entity.PickupBulkstockEntity;
import com.yuexunit.finance.project.entity.PickupDelayApplicationEntity;
import com.yuexunit.finance.project.entity.PickupExchangeContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.PickupExchangeContainerEntity;
import com.yuexunit.finance.project.entity.PickupExchangeEntity;
import com.yuexunit.finance.project.entity.ReceivablesEntity;
import com.yuexunit.finance.project.entity.lexicon.DeliveryMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.PickupMethodEnum;
import com.yuexunit.finance.project.service.ContainerBulkstockService;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceContractService;
import com.yuexunit.finance.project.service.PickupBulkstockService;
import com.yuexunit.finance.project.service.PickupDelayApplicationService;
import com.yuexunit.finance.project.service.PickupExchangeContainerBulkstockService;
import com.yuexunit.finance.project.service.PickupExchangeContainerService;
import com.yuexunit.finance.project.service.PickupExchangeService;
import com.yuexunit.finance.project.service.PickupInventoryService;
import com.yuexunit.finance.project.service.ReceivablesService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

/**
 * @ClassName: PickupApplicationCastor
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年11月26日 下午10:17:57
 */
public class BulkstockPledgeCastor {

	/** 提货申请/提前还款/赎货申请 */
	public static PickupApplicationEntity fromPickupApplication(FinanceApplicationEntity finance, PickupApplication info) {
		PickupApplicationEntity entity = new PickupApplicationEntity();
		BeanUtils.copyProperties(info, entity);
		entity.setPickupMethod(PickupMethodEnum.valueOf(info.getPickupMethod()));
		entity.setDeliveryMethod(DeliveryMethodEnum.valueOf(info.getDeliveryMethod()));
		entity.setDeliveryDate(DateUtil.parseDateInt(info.getDeliveryDate()));
		entity.setApplicant(finance.getEnterpriseName());
		entity.setApplicantId(FinanceSessionContext.getAccountId());

		entity.setFinanceNumber(finance.getFinanceNumber());
		entity.setEnterpriseId(finance.getEnterpriseId());
		entity.setEnterpriseName(finance.getEnterpriseName());
		return entity;
	}

	public static Collection<PickupBulkstockEntity> fromPickupInventory(List<ContainerInventoryEntity> inventories) {
		ContainerBulkstockService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockService.class);
		Map<Long, PickupBulkstockEntity> pickupBulkstocks = new HashMap<>(); // 相同货物的合并
		for (ContainerInventoryEntity cie : inventories) {
			List<ContainerBulkstockEntity> containerBulkstocks = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
			for (ContainerBulkstockEntity cbe : containerBulkstocks) {
				PickupBulkstockEntity pickupBulkstock = pickupBulkstocks.get(cbe.getBulkstockId());
				if (pickupBulkstock == null) {
					pickupBulkstock = new PickupBulkstockEntity();
					BeanUtils.copyProperties(cbe, pickupBulkstock);
					pickupBulkstock.setPickupId(cie.getPickupId());
					pickupBulkstock.setQuantity(BigDecimal.ZERO);
					pickupBulkstock.setPickup(BigDecimal.ZERO);
					pickupBulkstock.setVolume(BigDecimal.ZERO);
					pickupBulkstock.setWeight(BigDecimal.ZERO);
					pickupBulkstock.setValuationQuantity(BigDecimal.ZERO);
					pickupBulkstocks.put(cbe.getBulkstockId(), pickupBulkstock);
				}
				pickupBulkstock.setQuantity(pickupBulkstock.getQuantity().add(cbe.getQuantity()));
				pickupBulkstock.setWeight(pickupBulkstock.getWeight().add(cbe.getWeight()));
				pickupBulkstock.setVolume(pickupBulkstock.getVolume().add(cbe.getVolume()));
				pickupBulkstock.setValuationQuantity(pickupBulkstock.getValuationQuantity().add(cbe.getValuationQuantity()));
			}
		}
		return pickupBulkstocks.values();
	}

	private static void completeToPickupApplicationLineInfo(PickupApplicationLineInfo info, PickupApplicationEntity entity) {
		PickupInventoryService pickupInventoryService = ComponentFactory.loadClass(PickupInventoryService.class);
		FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		BeanUtils.copyProperties(entity, info, "interestInfo");
		info.setInterestInfo(entity.getInterestInfo());
		if (entity != null) {
			FinanceContractService financeContractService = ComponentFactory.loadClass(FinanceContractService.class);
			FinanceContractEntity contract = financeContractService.inquireFinanceIdContract(entity.getFinanceId(), 2);
			List<Long> inventoryIds = pickupInventoryService.inquirePickupInventoryIdList(entity.getPickupId());
			info.setPickupMethod(entity.getPickupMethod().ordinal());
			info.setPickupType(entity.getPickupType().ordinal());
			info.setProductType(finance.getProductType().ordinal());
			info.setDeliveryMethod(entity.getDeliveryMethod().ordinal());
			info.setApplicationState(entity.getApplicationState().ordinal());
			info.setDeliveryDate(DateUtil.formatDate(entity.getDeliveryDate()));
			info.setApplicantDateTime(entity.getApplicantDateTime());
			info.setExchangeStatus(entity.getExchangeStatus() == null ? 1 : entity.getExchangeStatus().ordinal());
			info.setEnterpriseName(entity.getEnterpriseName());
			if(entity.getFinalState() !=null){
				info.setFinalState(entity.getFinalState().intValue());
			}
			info.setContainerSize(inventoryIds.size());
			if (contract != null) {
				info.setFinanceContractSerialNumber(contract.getFinanceContractSerialNumber());
			}
			PickupBulkstockService pickupBulkstockService = ComponentFactory.loadClass(PickupBulkstockService.class);
			List<PickupBulkstockEntity> bulkstockEntities = pickupBulkstockService.inquirePickupBulkstockList(entity.getPickupId());
			BulkstockCastor.completeToPickupBulkstockList(bulkstockEntities, info.getPickupBulkstocks());
		}
	}

	public static PickupApplicationDetail toPickupApplicationDetail(PickupApplicationEntity entity) {
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		
		PickupApplicationDetail detail = new PickupApplicationDetail();
		if (entity == null) {
			return detail;
		}
		
		completeToPickupApplicationLineInfo(detail, entity);

		PickupInventoryService pickupInventoryService = ComponentFactory.loadClass(PickupInventoryService.class);
		List<Long> inventoryIds = pickupInventoryService.inquirePickupInventoryIdList(entity.getPickupId());
		if (inventoryIds != null && inventoryIds.size() > 0) {
			List<ContainerInventoryEntity> containerInventoryList = containerInventoryService.inquireContainerInventoryList(inventoryIds.toArray(new Long[inventoryIds.size()]));
			for (ContainerInventoryEntity cie : containerInventoryList) {
				ContainerInventory containerInventory = BulkstockCastor.toContainerInventory(cie, Boolean.FALSE);
				detail.getContainerInventorys().add(containerInventory);
			}
		}

		PickupExchangeContainerService pickupExchangeContainerService = ComponentFactory.loadClass(PickupExchangeContainerService.class);
		PickupExchangeContainerBulkstockService pickupExchangeContainerBulkstockService = ComponentFactory.loadClass(PickupExchangeContainerBulkstockService.class);
		PickupExchangeService pickupExchangeService = ComponentFactory.loadClass(PickupExchangeService.class);
		ReceivablesService receivablesService = ComponentFactory.loadClass(ReceivablesService.class);

		List<PickupExchangeContainerEntity> pickupExchangeContainerEntityList = pickupExchangeContainerService.inquirePickupExchangeContainerList(entity.getPickupId());
		List<PickupExchangeEntity> pickupExchangeEntityList = pickupExchangeService.inquirePickupExchangeList(entity);
		ReceivablesEntity receivables = receivablesService.inquireReceivablesFromPickupId(entity.getPickupId());
		
		if (null == receivables) {
			detail.setReceivablesDetail(null);
		} else {
			detail.setReceivablesDetail(FinanceLoanCastor.toReceivablesDetail(receivables));
		}

		if (pickupExchangeEntityList.size() > 0) {
			List<ExchangeBulkstockInfo> list = new ArrayList<ExchangeBulkstockInfo>();
			for (PickupExchangeEntity pee : pickupExchangeEntityList) {
				ExchangeBulkstockInfo exchangeBulkstockInfo = toExchangeBulkstockInfo(pee);
				list.add(exchangeBulkstockInfo);
			}
			detail.setExchangeBulkstockInfo(list);
		}

		if (pickupExchangeContainerEntityList.size() > 0) {
			List<ExchangeContainerInventory> list = new ArrayList<ExchangeContainerInventory>();
			for (PickupExchangeContainerEntity pece : pickupExchangeContainerEntityList) {
				if (StringUtil.isNotBlank(pece.getInventoryId())) {
					ContainerInventoryEntity cie = containerInventoryService.inquireContainerInventory(Long.valueOf(pece.getInventoryId()));
					if(cie==null)continue;
					ContainerInventory ci = BulkstockCastor.toContainerInventory(cie, Boolean.FALSE);
					detail.getExchangeContainerInventorys().add(ci);
				} else {
					List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventory(null, pece.getWaybillNumber(), pece.getCaseNumber());
					if (cies != null && !cies.isEmpty()) {
						ContainerInventoryEntity cie = cies.get(0);
						ContainerInventory ci = BulkstockCastor.toContainerInventory(cie, Boolean.FALSE);
						detail.getExchangeContainerInventorys().add(ci);
					}
				}
				ExchangeContainerInventory exchangeContainerInventory = toExchangeBulkstockInfo(pece);
				List<PickupExchangeContainerBulkstockEntity> pickupExchangeContainerBulkstockEntityList = pickupExchangeContainerBulkstockService.inquirePickupExchangeContainerBulkstockList(pece.getContainerId());
				if (pickupExchangeContainerBulkstockEntityList.size() > 0) {
					List<ExchangeContainerBulkstock> bList = new ArrayList<ExchangeContainerBulkstock>();
					for (PickupExchangeContainerBulkstockEntity pcbe : pickupExchangeContainerBulkstockEntityList) {
						ExchangeContainerBulkstock exchangeContainerBulkstock = toExchangeBulkstockInfo(pcbe);
						bList.add(exchangeContainerBulkstock);
					}
					exchangeContainerInventory.setExchangeContainerBulkstock(bList);
				}

				list.add(exchangeContainerInventory);
			}

			detail.setExchangeContainerInventory(list);
		}

		return detail;
	}

	private static ExchangeBulkstockInfo toExchangeBulkstockInfo(PickupExchangeEntity entity) {
		ExchangeBulkstockInfo info = new ExchangeBulkstockInfo();
		BeanUtils.copyProperties(entity, info);
		info.setMeasurement(entity.getMeasurement().ordinal());
		info.setEvaluateValuation(info.getEvaluatePrice() == null ? BigDecimal.ZERO : info.getEvaluatePrice().multiply(info.getValuationQuantity()));
		return info;
	}

	public static ExchangeContainerBulkstock toExchangeBulkstockInfo(PickupExchangeContainerBulkstockEntity entity) {
		ExchangeContainerBulkstock bulkstock = new ExchangeContainerBulkstock();
		BeanUtils.copyProperties(entity, bulkstock);
		bulkstock.setMeasurement(entity.getMeasurement().ordinal());
		return bulkstock;
	}

	private static ExchangeContainerInventory toExchangeBulkstockInfo(PickupExchangeContainerEntity entity) {
//		FinanceApplicationActionApi financeApplicationActionApi = ComponentFactory.loadClass(FinanceApplicationActionApi.class);
		ExchangeContainerInventory inventory = new ExchangeContainerInventory();
		BeanUtils.copyProperties(entity, inventory);
//		HandleSuitcaseResult hsr = financeApplicationActionApi.containerTaken(entity.getWaybillNumber(), entity.getCaseNumber());
//		if (hsr != null) {
//			inventory.setContainerTaken(hsr.getResult());
//		}
		return inventory;
	}

	public static PickupApplicationLineInfo toPickupApplicationLineInfo(PickupApplicationEntity entity) {
		PickupApplicationLineInfo info = new PickupApplicationLineInfo();
		completeToPickupApplicationLineInfo(info, entity);
		return info;
	}

	// =======================================================================================================================================================//
	/** 提货延期申请 */
	public static PickupDelayApplicationEntity fromPickupDelayApplication(PickupApplicationEntity pickup, String deliveryDate, BigDecimal estimateDelayAmount) {
		PickupDelayApplicationService pickupDelayApplicationService = ComponentFactory.loadClass(PickupDelayApplicationService.class);
		List<PickupDelayApplicationEntity> waits = pickupDelayApplicationService.inquireWaitPickupDelayApplication(pickup.getPickupId());
		if (waits != null && !waits.isEmpty()) {
			throw new BusinessException("已经有延期审批等待审核");
		}
		PickupDelayApplicationEntity delayEntity = new PickupDelayApplicationEntity();
		delayEntity.setFinanceId(pickup.getFinanceId());
		delayEntity.setFinanceNumber(pickup.getFinanceNumber());
		delayEntity.setPickupId(pickup.getPickupId());
		delayEntity.setPickupNumber(pickup.getPickupNumber());
		delayEntity.setEnterpriseId(pickup.getEnterpriseId());
		delayEntity.setEstimateDelayAmount(estimateDelayAmount);
		delayEntity.setSourceDeliveryDate(pickup.getDeliveryDate());
		delayEntity.setDeliveryDate(DateUtil.parseDateInt(deliveryDate));
		delayEntity.setApplicant(FinanceSessionContext.getAccountFullName());
		delayEntity.setApplicantId(FinanceSessionContext.getAccountId());
		delayEntity.setApplicantDateTime(DateUtil.now());
		return delayEntity;
	}

	private static void completeToPickupDelayApplicationLineInfo(PickupDelayApplicationLineInfo info, PickupDelayApplicationEntity entity) {
		BeanUtils.copyProperties(entity, info);
		info.setApplicationState(entity.getApplicationState().ordinal());
		info.setSourceDeliveryDate(DateUtil.formatDate(entity.getSourceDeliveryDate()));
		info.setDeliveryDate(DateUtil.formatDate(entity.getDeliveryDate()));
		info.setApplicantDatetime(entity.getApplicantDateTime());
		PickupBulkstockService pickupBulkstockService = ComponentFactory.loadClass(PickupBulkstockService.class);
		List<PickupBulkstockEntity> bulkstockEntities = pickupBulkstockService.inquirePickupBulkstockList(entity.getPickupId());
		BulkstockCastor.completeToPickupBulkstockList(bulkstockEntities, info.getPickupBulkstocks());
	}

	/** 提货延期申请 */
	public static PickupDelayApplicationDetail toPickupDelayApplicationDetail(PickupDelayApplicationEntity entity) {
		PickupDelayApplicationDetail info = new PickupDelayApplicationDetail();
		completeToPickupDelayApplicationLineInfo(info, entity);

		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		List<ContainerInventoryEntity> containerInventoryList = containerInventoryService.inquirePickupContainerInventoryList(entity.getPickupId());
		for (ContainerInventoryEntity cie : containerInventoryList) {
			info.getContainerInventorys().add(BulkstockCastor.toContainerInventory(cie, Boolean.FALSE));
		}
		return info;
	}

	/** 提货延期申请 */
	public static PickupDelayApplicationLineInfo toPickupDelayApplicationLineInfo(PickupDelayApplicationEntity entity) {
		PickupDelayApplicationLineInfo info = new PickupDelayApplicationLineInfo();
		completeToPickupDelayApplicationLineInfo(info, entity);
		return info;
	}

}
